<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>成远生产管控平台 - 单位信息</title>
    <link rel="stylesheet" href="./layui/css/layui.css"/>
    <script src="./layui/layui.js"></script>
    <script>
        // 全局配置
        window.appConfig = {
            // apiBaseUrl: 'http://localhost:8080' // 开发环境
            apiBaseUrl: 'http://59.110.144.74:8080' // 生产环境
        };
    </script>

    <style>
        body {
            padding: 20px;
        }
    </style>
</head>
<body>

<div class="layui-container" style="padding: 20px;">
    <form class="layui-form" id="unitForm" lay-filter="unitForm">
        <input type="hidden" name="id" id="unitId">

        <div class="layui-form-item">
            <label class="layui-form-label">单位名称</label>
            <div class="layui-input-block">
                <input type="text" name="unitName" id="unitName" required lay-verify="required|unitName"
                       placeholder="请输入单位名称" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="saveUnit">保存</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                <button type="button" class="layui-btn layui-btn-danger" onclick="window.history.back()">返回</button>
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['form', 'layer', 'jquery'], function () {
        const form = layui.form;
        const layer = layui.layer;
        const $ = layui.jquery;

        // 初始化数据（如果是编辑）
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode');
        const unitId = urlParams.get('id');
        const unitName = urlParams.get('unitName');

        if (mode === 'edit' && unitId) {
            $('#unitId').val(unitId);
            $('#unitName').val(unitName);
            form.render();
        }

        // 表单提交事件
        form.on('submit(saveUnit)', function (data) {
            const formData = data.field;
            const isEdit = !!formData.id;

            $.ajax({
                url: window.appConfig.apiBaseUrl +'/unit',
                method: isEdit ? 'PUT' : 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg(isEdit ? '更新成功' : '添加成功', { icon: 1 });
                        window.location.href = 'admin.html#unit';
                    } else {
                        layer.msg(res.message || '操作失败', { icon: 2 });
                    }
                },
                error: function (xhr) {
                    layer.msg('请求失败: ' + xhr.statusText, { icon: 2 });
                }
            });

            return false; // 阻止默认提交
        });
    });
</script>

</body>
</html>
